import { useEffect, useReducer } from "react"
import { TouchableOpacity, View, Text, StyleSheet, Alert } from "react-native"

/**
 * Type define
 */
type StateType = {count: number, disabled: boolean}
type UseCountDownType = (num?: number) => [number, boolean]
/**
 * Function component
 */
const Category = () => {
  const [count, disabled] = UseCountDown(0)

  const confirmClick = () => {
    Alert.alert('协议生效!')
  }

  return(
    <View style={styles.containerView}>
      <TouchableOpacity disabled={disabled} onPress={confirmClick}>
        <Text style={[styles.textStyle, disabled ? styles.disabledStyle : styles.enabledStyle]}> 
          {disabled ? '请仔细阅读本协议 ('+count+') 秒' : '请确认此协议'} 
        </Text>
      </TouchableOpacity>
    </View>
  )
}
/**
 * Style Sheet define
 */
const styles = StyleSheet.create({
  containerView: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  textStyle: {
    padding: 5
  },
  disabledStyle: {
    color: 'gray'
  },
  enabledStyle: {
    color: 'black'
  },
})
/**
 * Custom hook function: implement countdown feature
 * @param num Initial time, in seconds
 * @returns [Current seconds, Action disabled]
 */
const UseCountDown: UseCountDownType = (num: number = 10) => {
  // The function is the first parameter of the 'useReducer' hook
  const reducer = (prevState: StateType, action: string) => {
    switch (action) {
      // Start the countdown
      case 'start':
        return {...prevState, count: prevState.count -= 1};
      // Stop the timer
      case 'stop':
        return {...prevState, disabled: false};
      // Other condition
      default:
        return prevState;
    }
  }
  // The default state of the 'useReducer' hook
  const defaultState = {count: num, disabled: true}
  // Function to initialize the default state
  const initAction = (initState: StateType) => {
    return {...initState, count: Math.round(Math.abs(initState.count)) || 10}
  }
  // Use 'useReducer' hook
  const [state, dispatch] = useReducer(reducer, defaultState, initAction)
  // Use 'useEffect' hook
  useEffect(() => {
    // Create a timer
    const timerId = setTimeout(() => {
      if (state.count > 1) {
        dispatch('start')
      } else {
        clearTimeout(timerId)
        dispatch('stop')
      }
    }, 1000)
    return () => clearTimeout(timerId)
  }, [state.count])
  // Return result
  return [state.count, state.disabled]
}
export default Category